import member from '@src/store/member'
import base from '@src/store/base'
import {
	checkMemberAfterPay,
	checkMemberCartState,
	getCategoryAvailable,
	updateToNewCard,
	openMemberCard,
	checkWxCardState,
	checkSuperMemberStatus,
	authCheckMobile
} from '@src/api/member';
import memberPayBehavior from "@src/common/memberPayBehavior";
import {
	storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
import {
	parseCategoryIntro,
	parseCategoryRights,
	parsePrivileges,
	parseRechargeAwardRule,
	parseOpenCardGift
} from "@src/common/memberCardUtils";
import router from "@src/router";
import $cache from "@src/common/wxCache";
import chooseCardModule from './chooseCardModule'
import {
	_debounce
} from '@src/common/utils'
import {
	checkSmsCode
} from '../../api/member'
const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
let themeConfigMall = $cache.get('themeConfig-mall')

Component({
	behaviors: [storeBindingsBehavior, memberPayBehavior],
	storeBindings: [{
		store: member,
		fields: ['isMember', 'xhOpenId', 'memberName', 'categoryName', 'categoryId', 'cardOrder',
			'phone'
		],
		actions: ['getBaseInfo', 'syncWxCard'],
	}, {
		store: base,
		fields: ['themeColor', 'themeTitleColor', 'indexPageScene']
	}],
	data: {
		login: false,
		openCardBtnTitle: "立即开通",
		availableData: null,
		curIndex: 0,
		category: null,
		// 入口指定会员卡
		enterCategoryId: null,
		accountInfo: {},
		currentCardOrder: 0,
		wxCardState: {
			hasGet: false,
			hasActive: false,
		},
		billDetailModal: false,
		openCategoryId: "",
		customOpenRewards: [],
		// 超级会员
		superMemberStatus: null, //0已开通    80034未开通

		showPopup: false, // 是否显示弹窗
		smsText: '获取验证码',
		smsCode: '',
		smsPhone: '',
		needAuth: false,
		bindType: '', //  openIdBindDifferentPhone（走获取手机验证码） phoneBindDifferentOpenId（走获取手机验证码） alreadyExists（已是会员无需开卡） directOpenCard（返回手机号直接开卡）authToGetPhone（需授权获取手机号再开卡）
		phoneCode: '',
		isPassCode: false,
		memberIconList: [],
		selectMemberIcon: 0,
		loading: true,
		keyboardHeight: 0,
		isShowOpenCardBtn: false,
		isShowPopup: false
	},
	methods: {
		...chooseCardModule,
		filterList() {
			const { cardOrder, category, openCardGift, categoryRights, privileges, superMemberStatus, validPeriod } = this.data
			const memberIconList = [
				{
					id: 1,
					path: '../../static/vip/openCardGift.png',
					title: '开卡礼包'
				},
				{
					id: 2,
					path: '../../static/vip/memberCard.png',
					title: '会员卡权益'
				},
				{
					id: 3,
					path: '../../static/vip/birthDay.png',
					title: '生日特权'
				},
				{
					id: 4,
					path: '../../static/vip/memberDay.png',
					title: '会员日特权'
				},
				{
					id: 5,
					path: '../../static/vip/superMember.png',
					title: '超级会员'
				},
				{
					id: 6,
					path: '../../static/vip/timeLimit.png',
					title: '永久有效'
				},
			]
			this.setData({ selectMemberIcon: 0 })
			let list = []
			//开卡礼包
			cardOrder !== category.cardOrder && list.push({ ...memberIconList[0], openCardGift })
			// 会员卡权益
			categoryRights && categoryRights.length > 0 && list.push({ ...memberIconList[1], data: categoryRights })
			//生日特权
			const birthDayData = privileges.filter(item => item.privilegeType === 2)[0]
			birthDayData?.length && list.push({ ...memberIconList[2], data: birthDayData })
			//会员日特权
			let memberDay = privileges.filter(item => item.privilegeType === 1)
			memberDay = memberDay.length ? memberDay : null
			let superMember = superMemberStatus ? [{ title: '会员可在其他店铺享受优惠折扣' }] : null
			memberDay && list.push({ ...memberIconList[3], data: memberDay })
			superMember && list.push({ ...memberIconList[4], data: superMember })
			list.push({ ...memberIconList[5], title: (validPeriod + '有效') })
			this.setData({ memberIconList: list })
		},
		showPopupChange() {
			this.setData({
				isShowPopup: !this.data.isShowPopup
			})
		},
		selectChange(e) {
			const { index } = e.currentTarget.dataset
			this.setData({ selectMemberIcon: index })
		},
		async onLoad(options) {
			if (options.isNavMini) {
				const { marketingUUID } = options
				getApp().globalData.isNavMini = true
				getApp().globalData.marketingUUID = marketingUUID
			} else {
				this.setData({ isShowOpenCardBtn: true })
			}
			let enterCategoryId = options.categoryId;
			if (enterCategoryId) {
				this.setData({
					enterCategoryId: Number(enterCategoryId)
				})
			}
		},
		async onShow() {
			const appOps = wx.getEnterOptionsSync()
			const token = $cache.get('token')
			// if (appOps.scene === 1037 && token) {
			// 	themeConfigMall && this.initCheckPhone.call(this)
			// 	!themeConfigMall && base.themeConfig(this.initCheckPhone.call(this))
			// }
		},
		onAnon() {
			this.fetchData();
			this.checkSuperMemberStatusFun()
			this.setData({
				login: false
			})
			const appOps = wx.getEnterOptionsSync()
			if (appOps.scene === 1037) {
				return this.selectComponent("#login").requireLogin()
			}
		},
		handleLogin() {
			this.fetchData();
			this.checkSuperMemberStatusFun()
			this.getBaseInfo();
			this.setData({
				login: true
			}, () => {
				const appOps = wx.getEnterOptionsSync()
				if (appOps.scene === 1037) {
					base.themeConfig(this.initCheckPhone.call(this))
				}
			})
		},
		handleViewBillDetail() {
			this.setData({
				billDetailModal: !this.data.billDetailModal
			})
		},
		handleCloseBillDetail() {
			this.setData({
				billDetailModal: false
			})
		},
		onLogin() {
			this.fetchData();
			this.checkAfterPayMember();
			this.checkWxCardStateFunc();
			this.checkSuperMemberStatusFun()
			const appOps = wx.getEnterOptionsSync()
			// if (appOps.scene === 1037) {
			// 	base.themeConfig(this.initCheckPhone.call(this))
			// }
		},
		autoOPenCard() {
			const { availableData, isMember, login } = this.data
			const [freeCard] = availableData.filter(item => (!item.category.rechargeCost && !item.category.payCost))
			if (!freeCard) {
				this.setData({ isShowOpenCardBtn: true })
			}
			if (isMember || !login || !freeCard) return
			this.handleNewOpenCard(freeCard.category)
		},
		onPullDownRefresh() {
			wx.stopPullDownRefresh();
			this.fetchData();
		},
		handleChangeIndex(e) {
			let index = e.detail.current
			this.setData({
				showBtns: true // 切换时 显示按钮
			});

			if (this.data.availableData && this.data.availableData.length > index) {
				this.resetCurCard(this.data.availableData[index]);
			}
		},
		codeFocus(e) {
			let keyboardHeight = e.detail.height
			this.setData({ keyboardHeight })
		},
		codeBlur() {
			this.setData({ keyboardHeight: 0 })
		},
		fetchData() {
			getCategoryAvailable().then(res => {
				if (res.code === 0) {
					let availableData = res.data
					this.setData({
						"availableData": availableData,
						loading: false
					})
					if (availableData && availableData.length > 0) {
						if (this.data.enterCategoryId) {
							let items = availableData.filter(item => item.category.id === this.data
								.enterCategoryId)
							for (let i = 0; i < availableData.length; i++) {
								let item = availableData[i];
								if (item.category.id === this.data.enterCategoryId) {
									this.setData({
										enterCategoryId: null,
										curIndex: i
									});
									this.resetCurCard(items[0]);
									return;
								}
							}
						}
						if (this.data.curIndex && this.data.curIndex < availableData.length) {
							this.resetCurCard(availableData[this.data.curIndex]);
						} else {
							this.setData({
								curIndex: 0
							})
							this.resetCurCard(availableData[0]);
						}
					}
				}
			})
		},
		//开卡按钮
		handleOpenCardBtn: _debounce(function () {
			if (!this.data.login) {
				const loginComp = this.selectComponent("#login");
				loginComp.requireLogin();
				return;
			}

			// 先注释下以前的逻辑
			if (this.data.category.cardOrder > this.data.cardOrder) {
				if (!this.data.category.firstYearFree && !this.data.billDetailModal) {
					this.setData({
						billDetailModal: true
					})
				} else {
					this.handleNewOpenCard()
				}
				// this.handleNewOpenCard()
				// router.push({
				//   name: "member/activeMemberCard",
				//   params: {
				//     categoryId: this.data.category.id
				//   }
				// })
			}
		}, 250),

		//新逻辑，不跳激活页面
		handleNewOpenCard(notNeedPayCard = {}) {
			let resultData = {}

			if (this.data.wxCardState.hasGet && !this.data.wxCardState.hasActive) {
				resultData = this.selectComponent("#person-info").validItemArr();
				if (!resultData) {
					return;
				}
			}
			wx.showLoading({
				title: "开卡中...",
				mark: true
			});
			if (!themeConfigMall.mercNo) {
				themeConfigMall = $cache.get('themeConfig-mall')
			}
			let data = {
				categoryId: this.data.openCategoryId,
				intoWay: this.data.indexPageScene.receiveWay,
				channel: 2,
				data: resultData,
				scene: this.data.indexPageScene.scene,
				mercNo: themeConfigMall.mercNo,
				phone: this.phone || this.data.phone || null
			};
			if (JSON.stringify(notNeedPayCard) !== '{}') {
				const { id } = notNeedPayCard
				data = {
					...data,
					categoryId: id,

				}
			}
			let reqApi;
			if (this.data.isMember) {
				reqApi = updateToNewCard
			} else {
				reqApi = openMemberCard
			}

			reqApi(data).then(res => {
				wx.hideLoading();
				if (res.code === 0) {
					this.setData({
						openCardData: res.data,
						// bindType: ''
					})
					if (res.data.needPay) {
						let payData = {
							orderNo: res.data.orderCode,
							payChannels: ["wx"],
							hasDiscount: false
						}
						this.toMemberPay(payData).then(res => {
							this.syncStateFunc();
						}).catch(res => {
							console.info('支付error', res)
						});
					} else {
						this.syncStateFunc();
					}
				} else {
					wx.showToast({
						title: res.msg,
						icon: "none",
						duration: 3000
					});
				}
				this.handleCloseBillDetail()
			}).catch(err => {
				console.log(err)
				// wx.hideLoading();
				this.handleCloseBillDetail()
			})
		},
		checkAfterPayMember() {
			// 检查支付即会员
			checkMemberAfterPay().then(res => {
				if (res.code === 0 && res.data) {
					wx.showModal({
						title: "温馨提示",
						content: "你有一个会员资格待激活",
						confirmText: "去激活",
						success: (r) => {
							if (r.confirm) {
								router.redirectTo({
									name: "activeMineCard"
								})
							}
							if (r.cancel) {
								resolve(res.data)
							}
						}
					})
				}
			})
		},
		getPhoneNumber(e) {
			if (!this.data.login) {
				const loginComp = this.selectComponent("#login");
				loginComp.requireLogin();
				return;
			}
			if (!e.detail.iv) {
				wx.showToast({
					title: "手机号获取失败，请重试",
					icon: "none",
					duration: 1500
				});
				return;
			}
			let reqData = {
				ivStr: e.detail.iv,
				encryptedData: e.detail.encryptedData,
			}

			checkMemberCartState(reqData).then(res => {
				const themeConfigMall = $cache.get('themeConfig-mall')
				this.phone = res.data.phone
				authCheckMobile({
					data: {
						phone: res.data.phone
					},
					header: {
						xhOpenId: this.data.xhOpenId || null,
						mercNo: themeConfigMall.mercNo
					}
				}).then(result => {
					if (result.code === 0 && result.data.type) {
						return this.setData({
							bindType: result.data.type,
							showPopup: true,
							member: result.data.member,
							smsPhone: res.data.phone ? this.filterMobile(res.data
								.phone) : ''
						}, () => {
							if (result.data.type === 'openIdBindDifferentPhone' ||
								result.data.type === 'phoneBindDifferentOpenId') {
								this.handleSmsCode()
							}
						})
					} else {
						// if (miniProgram) {
						// 	let phone = miniProgram.phone //收银台手机号
						// 	let _phone = res.data.phone //当前手机号
						// 	if (phone !== _phone) {
						// 		wx.showModal({
						// 			title: "授权提示",
						// 			content: "您授权的手机号与收银台中授权的手机号不一致，请重新授权",
						// 			showCancel: false,
						// 			success: (res) => {}
						// 		});
						// 		return
						// 	}
						// }

						if (res.data.mergeCustomer) {
							// 重新设置token
							let expireTime = $cache.ttl("token");
							$cache.setSync("token", res.data.newToken, expireTime);
							wx.showModal({
								title: "您已经是会员~",
								content: "返回首页",
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										router.redirectTo({
											name: "index"
										})
									}
								}
							});
						} else if (res.data.isOfflineMember) {
							router.push({
								name: "member/bindOldMemberConfirm",
								success: (routerRes => {
									routerRes.eventChannel.emit(
										'oldMemberData', {
										'ivStr': reqData.ivStr,
										'encryptedData': reqData
											.encryptedData,
										'oldMemberInfo': res.data
									})
								})
							})
						} else {
							//todo 这里是新逻辑
							if (!this.data.category.firstYearFree && !this.data
								.billDetailModal) {
								this.setData({
									billDetailModal: true
								})
							} else {
								this.handleNewOpenCard()
							}
							//跳一键激活页面
							// router.push({
							//   name: "member/activeMemberCard",
							//   params: {
							//     categoryId: this.data.category.id
							//   }
							// })
						}

					}
				})
			})
		},
		handleLoginFunc() {
			if (!this.data.login) {
				const loginComp = this.selectComponent("#login");
				loginComp.requireLogin();
				return;
			}
		},
		closeSms() {
			const appOps = wx.getEnterOptionsSync()
			if(appOps.scene === 1037) {
				wx.navigateBackMiniProgram()
			}
			this.setData({showPopup:false})
		},
		handleShowShops(e) {
			let shopIds = e.currentTarget.dataset.shop;
			this.selectComponent("#shop-list").open(shopIds);
		},
		handleSuperShowShops() {
			// this.selectComponent("#superShop-list").open();
			router.push({
				name: 'member/cooperativeMerchant',
			});
		},
		resetCurCard(card) {
			let category = card.category;
			let privileges = card.privileges;
			let rechargeAward = card.rechargeAward;
			let introList = parseCategoryIntro(category);
			let categoryRights = parseCategoryRights(category, rechargeAward).concat(parseRechargeAwardRule(
				rechargeAward));
			let validPeriod = category.validPeriod + "年";
			if (category.validPeriod == 0) {
				validPeriod = "永久"
			}
			privileges = parsePrivileges(privileges);
			let openCardGift = parseOpenCardGift(category, card.openCardCouponAward, true);
			let currentCardOrder = category.cardOrder;
			let openCardBtnTitle = '立即开通'
			if (category.payType === 1) {
				openCardBtnTitle = "立即开卡";
			} else if (category.payType === 2) {
				openCardBtnTitle = `付费${category.payCost / 100}元开通`;
				if (!category.firstYearFree) {
					openCardBtnTitle = `付费${(category.payCost + category.annualFee) / 100}元开通`;
				}
			} else if (category.payType === 3) {
				openCardBtnTitle = `预存${category.rechargeCost / 100}元开通`;
			}
			if (categoryRights.length > 0) {
				categoryRights.forEach(item => {
					if (item.iconName) {
						if (item.iconName.substr(0, 4) == "icon") {
							item.icon = true
						} else {
							item.icon = false
						}
					}
				})
			}
			let customOpenRewards = [];
			if (category.customGift) {
				customOpenRewards = JSON.parse(category.customGift)
			}
			if (category.instructions) {
				introList.push(category.instructions)
			}

			this.setData({
				category,
				categoryRights,
				introList,
				privileges,
				rechargeAward,
				validPeriod,
				openCardGift,
				openCardBtnTitle,
				currentCardOrder,
				customOpenRewards
			}, () => {
				this.filterList()
			})
			this.setData({
				openCategoryId: this.data.category.id
			})
		},
		//后面copy过来的方法
		async syncStateFunc() {
			if (this.data.isPassCode) {
				const {
					bindType,
					smsCode
				} = this.data
				console.log(this.data)
				const miniProgram = $cache.get('miniProgram') || {}
				const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
				const params = {
					mercNo: miniProgram.storeNo || null,
					phone: this.phone,
					type: bindType ? bindType : '',
					phoneCode: smsCode,
					businessId: extConfig.businessId || null,
					xsOpenId: miniProgram.xsOpenId || null
				}
				const themeConfigMall = $cache.get('themeConfig-mall') || {}
				checkSmsCode({
					data: params,
					header: {
						xhOpenId: this.data.xhOpenId || null,
						mercNo: themeConfigMall.mercNo
					}
				})
					.then(res => {
						this.setData({
							bindType: ''
						})
					})
			}

			const appOps = wx.getEnterOptionsSync()
			if (appOps.scene === 1037) {
				const marketingUUID = getApp().globalData.marketingUUID
				wx.navigateBackMiniProgram({extraData: {marketingUUID},success:() => {
					getApp().globalData.marketingUUID = ''
				}})
			} else {
				const { isMember } = this.data
				const text = isMember ? '升级卡成功' : '恭喜您成为会员'
				wx.showToast({
					title: text,
					icon: 'none',
					success: () => {
						setTimeout(() => {
							wx.navigateBack()
						}, 2000)
					}
				})
				// wx.showModal({
				// 	title: "温馨提示",
				// 	content: "开通成功",
				// 	showCancel: false,
				// 	confirmText: "回首页",
				// 	success(res) {
				// 		if (res.confirm) {

				// 		}
				// 	}
				// });
			}

			// 刷新会员数据
			// if (!this.data.wxCardState.hasGet) {
			// 	this.syncWxCard();
			// } else {
			// 	wx.showModal({
			// 		title: "温馨提示",
			// 		content: "开通成功",
			// 		showCancel: false,
			// 		confirmText: "回首页",
			// 		success(res) {
			// 			if (res.confirm) {
			// 				router.push({
			// 					name: 'index'
			// 				})
			// 			}
			// 		}
			// 	});
			// }


			this.getBaseInfo();
		},
		checkWxCardStateFunc() {
			checkWxCardState().then(res => {
				if (res.code === 0) {
					this.setData({
						wxCardState: {
							hasActive: res.data.hasActive,
							hasGet: res.data.hasGet
						}
					})
				}
			})
		},
		// 查询是否开通超级会员
		checkSuperMemberStatusFun() {
			let businessId = extConfig.businessId;
			let from = {
				businessId
			}
			checkSuperMemberStatus(from).then(res => {
				this.setData({
					superMemberStatus: res.data
				})
			})
		}
	}
})
